package com.skymxc.skin

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.util.Log
import androidx.collection.ArrayMap
import androidx.core.view.LayoutInflaterCompat
import java.util.*

/**
 * <p>
 *
 * </p>
 *
 * @author 孟祥超
 * <p>
 * date: 2021/9/20  10:24 下午
 */
class ActivityLifecycle (private val mObservable:Observable):Application.ActivityLifecycleCallbacks {

    private val mLayoutInflaterFactories = ArrayMap<Activity,SkinLayoutInflaterFactory>()
    @SuppressLint("SoonBlockedPrivateApi")
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        //这个方法，是在 Activity 里的 setContentView 之前调用的

      // 收集 activity 内可以换肤的 view 及关联属性

        /**
         * 更新状态栏
         */
        updateStatusBarColor(activity)
        val layoutInflater = activity.layoutInflater
        try {//Android 布局加载器 使用 mFactorySet 标记是否设置过Factory
            //如设置过抛出一次
            //设置 mFactorySet 标签为false
            val field = layoutInflater.javaClass.getDeclaredField("mFactorySet")
            field.isAccessible = true
            field.setBoolean(layoutInflater, false)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        //使用factory2 设置布局加载工程
        val skinLayoutInflaterFactory = SkinLayoutInflaterFactory(activity)
        Log.e("ActivityLifecycle", "onActivityCreated: factory:${layoutInflater.factory2}", )
        LayoutInflaterCompat.setFactory2(layoutInflater,skinLayoutInflaterFactory)
        mObservable.addObserver(skinLayoutInflaterFactory)
    }

    override fun onActivityStarted(activity: Activity) {

    }

    override fun onActivityResumed(activity: Activity) {

    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        val remove = mLayoutInflaterFactories.remove(activity)
        mObservable.deleteObserver(remove)
    }
}